package bit2;

public class BinarySearchTree {
    static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        public TreeNode(int val) {
            this.val = val;
        }
    }
    public TreeNode root;
    //查找key值位于树的位置
    public TreeNode search(int key) {
        TreeNode cur=root;
        if (cur==null){
            return null;
        }
        while (cur!=null){
            if (key>cur.val){
                cur=cur.right;
            }
            else if (key<cur.val){
                cur=cur.left;
            }
            else {
                return cur;
            }
        }
        return null;
    }
    //将val值插入二叉树中
    public void insertTree(int val){
        TreeNode cur=root;
        TreeNode prev=null;
        TreeNode node=new TreeNode(val);
        while (cur!=null){
            prev=cur;
            if (val>cur.val){
                cur=cur.right;
            }
            else {
                cur=cur.left;
            }
        }
        if (prev.val>val){
            prev.left=node;
        }
        else {
            prev.right=node;
        }
    }
    public void remove(int key) {
        TreeNode cur = root;
        TreeNode parent = null;
        while (cur!=null){
            if (cur.val<key){
                parent=cur;
                cur=cur.right;
            }
            else if(cur.val>key){
                parent=cur;
                cur=cur.left;
            }
            else {
                removeNode(parent,cur);
            }
        }
    }
    //删除结点
    public void removeNode(TreeNode parent,TreeNode cur){
        if (cur.left==null){
            if (cur==root){
                cur=cur.right;
            }
            else if(parent.left==cur){
                parent.left=cur.right;
            }
            else if(parent.right==cur){
                parent.right=cur.right;
            }
        }
        else if(cur.right==null){
            if (cur==root){
                cur=cur.left;
            }
            else if(parent.left==cur){
                parent.left=cur.left;
            }
            else {
                parent.right=cur.left;
            }
        }
        else if(cur.left!=null&&cur.right!=null){
            TreeNode target=cur.right;
            TreeNode prev=cur;
            while (target.left!=null){
                prev=target;
                target=target.left;
            }
            cur.val=target.val;
            if (prev.left==target){
                prev.left=target.right;
            }
            else {
                prev.right=target.right;
            }
        }
    }
}
